package com.sise.cn.api.common.service;

import com.sise.cn.api.common.po.Order;
import com.sise.cn.api.common.po.OrderItem;
import com.sise.cn.api.common.po.Product;
import com.sise.cn.api.enumerate.ServerResponseEnum;
import com.sise.cn.api.exception.OrderException;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 龚秀峰
 * @version 1.0
 * @date 2020/6/15 19:21
 * 订单项关联商品的检查
 */
@Slf4j
public class OrderItemAssociateProductHandler extends BaseOrderHandler {
    public OrderItemAssociateProductHandler() {
        super("订单项关联商品检查处理");
    }
    @Resource
    private OrderItemService orderItemService;
    @Resource
    private ProductService productService;

    @Override
    public boolean processOrder(Order order) {
        final List<Long> orderItemIds = order.getOrderItemIds();
        if(orderItemIds == null || orderItemIds.isEmpty()){
            log.error("当前Order的订单项ID列表为空！");
            throw new OrderException(ServerResponseEnum.ORDER_RELATION_NONE);
        }
        for (Long orderItemId : orderItemIds) {
            final OrderItem orderItem = orderItemService.getOrderItemById(orderItemId);
            if(orderItem == null){
                log.error("根据Id:{}无法找到OrderItem!",orderItemId);
                throw new OrderException(ServerResponseEnum.ORDER_ITEM_SELECT_FAIL);
            }
            if(orderItem.getProductId() == null){
                log.error("OrderItem(ID为{})的productId为空!",orderItemId);
                throw new OrderException(ServerResponseEnum.ORDER_ITEM_ASSOCIATE_PRODUCT_NONE);
            }
            final Product product = productService.getProductById(orderItem.getProductId());
            if(product == null){
                log.error("根据Id:{}无法找到Product!",orderItem.getProductId());
                throw new OrderException(ServerResponseEnum.ORDER_ITEM_ASSOCIATE_PRODUCT_ERROR);
            }
        }
        return true;
    }
}
